//
//  HomePageViewController.m
//  product_B
//
//  Created by lanou on 16/5/26.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "HomePageViewController.h"
#import "HomePageMainModel.h"
#import "ScrollWithArrayView.h"
#import "HomePageNoteViewController.h"
#import "HomePagePreviousViewController.h"
#import "SmallScrollView.h"

@interface HomePageViewController () <UIScrollViewDelegate,HomePageScrollDelegate>
@property (nonatomic,strong)ScrollWithArrayView *listScrollView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UIView *smallView;
@property (nonatomic,assign)NSInteger index;
@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"ENO";
    self.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:22];
    
    self.dataArray = [[NSMutableArray alloc]init];
    
    [self netRequest];
    _smallView = [[UIView alloc]initWithFrame:CGRectMake(0, kHeight - 70 - 25, kWidth, 95 - 49)];
    _smallView.backgroundColor = [UIColor clearColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(20, 0, 25, 25);
    button.backgroundColor = [UIColor clearColor];
    [button addTarget:self action:@selector(noteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_smallView addSubview:button];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake(kWidth - 107, 0, 25, 25);
    button1.backgroundColor = [UIColor clearColor];
    [button1 addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_smallView addSubview:button1];
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    button2.frame = CGRectMake(kWidth - 40, 0, 25, 25);
    button2.backgroundColor = [UIColor clearColor];
    [button2 addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_smallView addSubview:button2];
}
- (IBAction)noteButtonAction:(UIButton *)sender {
   
    NSInteger index = self.listScrollView.scrollView.contentOffset.x/kWidth;
    HomePageMainModel *model = self.dataArray[index];
    HomePageNoteViewController *homePageNoteVC = [[HomePageNoteViewController alloc]init];
    homePageNoteVC.model = model;
    
    [self.navigationController pushViewController:homePageNoteVC animated:YES];
    
}
- (IBAction)likeButtonAction:(UIButton *)sender {
    _likeLabel.text = [NSString stringWithFormat:@"%ld",_likeLabel.text.integerValue + 1];
}
- (IBAction)shareButtonAction:(UIButton *)sender {

    HomePageMainModel *currentModel = _dataArray[_index];
    
    //1、创建分享参数
    //            NSArray* imageArray = @[[UIImage imageNamed:@"分享.png"]];

    NSArray *imageArray = @[currentModel.hp_img_original_url];
    // （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:currentModel.hp_content
                                         images:imageArray
                                            url:[NSURL URLWithString:currentModel.web_url]
                                          title:currentModel.hp_author
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）//要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
        
        [ShareSDK showShareActionSheet:nil
         
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               [self alert:@"分享成功"];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               [self alert:@"分享失败"];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];
    }
}


- (void)netRequest{
   
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://v3.wufazhuce.com:8000/api/hp/more/0" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (self.dataArray.count != 0) {
            [self.dataArray removeAllObjects];
        }
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = responseDic[@"data"];
        for (NSDictionary *dic in dataArray) {
            HomePageMainModel *model = [[HomePageMainModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.listScrollView = [[ScrollWithArrayView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64 - 49  ) modelArray:self.dataArray];
            self.listScrollView.layer.shadowColor = [UIColor grayColor].CGColor;
            self.listScrollView.scrollView.delegate = self;
            self.listScrollView.scrollDelegate = self;
            [self.listScrollView begin:self.listScrollView.size];
            NSInteger index = self.listScrollView.scrollView.contentOffset.x/kWidth;
            HomePageMainModel *model = self.dataArray[index];
            self.likeLabel.text = [NSString stringWithFormat:@"%@",model.praisenum];
            [self.view addSubview:_listScrollView];
            [self.view addSubview:_smallView];
      
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    _index = (int)self.listScrollView.scrollView.contentOffset.x % (int)kWidth;
    if (_index == 0) {
        
        
    }
    
}
- (void)clickedWithContentOffset:(CGFloat)offSet{
    if (offSet < kHeight - 160 - 10) {
        self.smallView.hidden = NO;
    }else{
        self.smallView.hidden = YES;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = self.listScrollView.scrollView.contentOffset.x/kWidth;
    CGFloat index1 = self.listScrollView.scrollView.contentOffset.x/kWidth;
    HomePageMainModel *model = self.dataArray[index];
    self.likeLabel.text = [NSString stringWithFormat:@"%@",model.praisenum];
    if (index <= 0) {
        [_listScrollView removeFromSuperview];
        [self netRequest];
    }else if (index1 > self.dataArray.count-1){
        HomePagePreviousViewController *homePagePreviousVC = [[HomePagePreviousViewController alloc]init];
        [self.navigationController pushViewController:homePagePreviousVC animated:YES];
    }
    if (![scrollView isMemberOfClass:[ScrollWithArrayView class]]) {
        NSInteger index2 =scrollView.contentOffset.x / kWidth;
        
        NSString *size = _listScrollView.sizeArray[index2];
        [_listScrollView begin:size.floatValue];
    }
    
    
}

- (void)alert:(NSString *)string{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
